package com.whiteape.book.core.engine;

import com.whiteape.book.utils.StringUtils;

import org.seimicrawler.xpath.JXDocument;
import org.seimicrawler.xpath.JXNode;

import java.util.ArrayList;
import java.util.List;

/**
 * xpath引擎
 */
public class XPathEngine {

    public static String getString(String html, String rule) {
        if (StringUtils.isEmpty(rule)) {
            return "";
        }
        html = preProcess(html);
        JXDocument document = JXDocument.create(preProcess(html));
        return (String)document.selOne(rule);
    }

    public static List<String> getStringList(String html, String rule) {

        List<String> result = new ArrayList<>();
        if (StringUtils.isEmpty(rule)) {
            return result;
        }
        JXDocument document = JXDocument.create(preProcess(html));
        List<JXNode> jxNodeList = document.selN(rule);
        for (JXNode node : jxNodeList) {
            result.add(node.toString());
        }
        return result;

    }

    public static List<JXNode> getElementList(String html, String rule) {
        List<JXNode> result = new ArrayList<>();
        if (StringUtils.isEmpty(rule)) {
            return result;
        }
        JXDocument document = JXDocument.create(preProcess(html));
        result = document.selN(rule);
        return result;
    }

    private static String preProcess(String html) {
        if (html.endsWith("</td>")) {
            html = String.format("<tr>%s</tr>", html);
        }
        if (html.endsWith("</tr>") || html.endsWith("</tbody>")) {
            html = String.format("<table>%s</table>", html);
        }
        return html;
    }
}
